# OY Project Auto Deploy Script
# Usage: .\deploy-simple.ps1

$SERVER_IP = "154.219.117.72"
$SERVER_USER = "root"
$REMOTE_PATH = "/var/www/oy-promotion"

Write-Host "================================" -ForegroundColor Cyan
Write-Host "OY Auto Deploy" -ForegroundColor Green
Write-Host "================================" -ForegroundColor Cyan
Write-Host ""

Write-Host "Server: $SERVER_USER@$SERVER_IP" -ForegroundColor Cyan
Write-Host "Path: $REMOTE_PATH" -ForegroundColor Cyan
Write-Host ""

# Step 1: Build
Write-Host "[1/5] Building project..." -ForegroundColor Yellow
npm run build

if ($LASTEXITCODE -ne 0) {
    Write-Host "Build failed!" -ForegroundColor Red
    exit 1
}
Write-Host "Build success!" -ForegroundColor Green

# Step 2: Compress
Write-Host "`n[2/5] Compressing files..." -ForegroundColor Yellow
if (Test-Path "dist.zip") {
    Remove-Item "dist.zip"
}
Compress-Archive -Path dist\* -DestinationPath dist.zip
Write-Host "Compress success!" -ForegroundColor Green

# Step 3: Upload
Write-Host "`n[3/5] Uploading to server..." -ForegroundColor Yellow
scp dist.zip ${SERVER_USER}@${SERVER_IP}:/tmp/

if ($LASTEXITCODE -ne 0) {
    Write-Host "Upload failed!" -ForegroundColor Red
    exit 1
}
Write-Host "Upload success!" -ForegroundColor Green

# Step 4: Deploy on server
Write-Host "`n[4/5] Deploying on server..." -ForegroundColor Yellow

# 清理旧文件
ssh ${SERVER_USER}@${SERVER_IP} "sudo rm -rf ${REMOTE_PATH}/*"

# 解压文件
ssh ${SERVER_USER}@${SERVER_IP} "sudo unzip -o /tmp/dist.zip -d ${REMOTE_PATH}/"

# 设置权限
ssh ${SERVER_USER}@${SERVER_IP} "sudo chown -R nginx:nginx ${REMOTE_PATH} 2>&1 || sudo chown -R www-data:www-data ${REMOTE_PATH} 2>&1 || echo 'Chown skipped'"

ssh ${SERVER_USER}@${SERVER_IP} "sudo chmod -R 755 ${REMOTE_PATH}"

# 重启 nginx
ssh ${SERVER_USER}@${SERVER_IP} "sudo systemctl restart nginx 2>&1 || sudo service nginx restart 2>&1 || echo 'Nginx restart skipped'"

# 清理临时文件
ssh ${SERVER_USER}@${SERVER_IP} "rm /tmp/dist.zip"

Write-Host "Deploy success!" -ForegroundColor Green

# Step 5: Cleanup
Write-Host "`n[5/5] Cleaning up..." -ForegroundColor Yellow
Remove-Item "dist.zip"

Write-Host "`nDeploy completed!" -ForegroundColor Green
Write-Host "Visit: http://${SERVER_IP}" -ForegroundColor Cyan
Write-Host ""
